<!DOCTYPE html>
<html>

<head>
    <title>Bootstrap-select 多选下拉框实现</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
    <link href="https://cdn.bootcss.com/bootstrap-select/1.12.1/css/bootstrap-select.min.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
    <script src="https://cdn.bootcss.com/bootstrap-select/1.12.1/js/bootstrap-select.min.js"></script>
</head>

<body>
<div class="form-group">
    <label class="col-lg-1 control-label">水果类型：</label>
    <div class="col-lg-6">
        <select id="fruits" class="selectpicker show-menu-arrow form-control" multiple>
<!--            <option value="0">苹果</option>-->
            <option value="1">菠萝</option>
            <option value="2">香蕉</option>
            <option value="3">火龙果</option>
            <option value="4">梨子</option>
            <option value="5">草莓</option>
            <option value="6">哈密瓜</option>
            <option value="7">哈密瓜</option>
            <option value="8">哈密瓜</option>
            <option value="10">哈密瓜</option>
            <option value="9">哈密瓜</option>
            <option value="14">哈密瓜</option>
            <option value="11">哈密瓜</option>
            <option value="12">哈密瓜</option>
            <option value="13">哈密瓜</option>
            <option value="20">哈密瓜</option>
        </select>
    </div>
    <button class="col-lg-1" onclick="getVal()">获取值</button>
</div>
<script>
    $(function(){
        //截取字符串加入数组，加载多选下拉框默认选项
        if($("#text").val()!=""){}
        var str = "1,2,3,4,5,10";
        var arr = StringToArray(str,",")
        console.log(arr)
        // console.log(StringToArray(str,","));
        $('#fruits').selectpicker('val', arr);   //
    })
    //字符串转换数组
    function StringToArray(str,substr){
        var arrTmp = new Array();
        if(substr ==""){
            arrTmp.push(str);
            return arrTmp;
        }
        var i=0,j=0,k=str.length;
        while(i<k) {
            j = str.indexOf(substr, i);
            if (j != -1) {
                if (str.substring(i, j) != "") {
                    arrTmp.push(str.substring(i, j))
                }

                i = j + 1;
            } else {
                if (str.substring(i, k) != "") {
                    arrTmp.push(str.substring(i, k));
                }
                i = k;
            }
        }

        return  arrTmp;
    }
</script>
</body>

</html>